package com.project.myshop.web.controller;

import com.project.myshop.common.Const;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 父类baseSerlvet 作为所有自定义servlet|controller 的父类
 * 协助处理 处理请求方法的调用方法以及响应的操作
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //this 当前对象的实例
        String method=req.getParameter("method");
        //判断method是否为null
        try {
            //1 获取当前对象的实例
            Class<? extends HttpServlet> aClass = this.getClass();
            //2 直接通过 方法名和参数列表来查询方法
            Method target=aClass.getMethod(method,HttpServletRequest.class,HttpServletResponse.class) ;
             //3 通过反射调用方法 优先执行调用方法，回到方法调用处
            String response =(String) target.invoke(this, req, resp);
            //在这个位置帮我们完成 转发 重定向 字符串写出
            if (response != null) {
                //转发
                if (response.contains(Const.FORWARD)) {
                    req.getRequestDispatcher(response.replace(Const.FORWARD,"")).forward(req,resp);
                }else if(response.contains(Const.REDIECT)){
                    resp.sendRedirect(response.replace(Const.REDIECT,""));
                }else {
                    resp.getWriter().println(response);
                }
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            //异常处理 处理调用出现找不到方法异常
            req.setAttribute("msg","404 找不到啦 哈哈哈哈");
            req.getRequestDispatcher("message.jsp").forward(req,resp);

        }

    }
}
